import requests
import json
# 创建一个 Session 对象
session = requests.Session()

# 访问登录页面以获取 CSRF 令牌或其他必要的 cookie
login_url = "https://yueshushu.top/Stock/login"
response = session.get(login_url)

# 提取 CSRF 令牌（如果有的话）
# 假设 CSRF 令牌存在于 HTML 中的一个隐藏输入字段中
csrf_token = None
if response.status_code == 200:
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(response.text, 'html.parser')
    csrf_token_input = soup.find('input', {'name': 'csrf_token'})
    if csrf_token_input:
        csrf_token = csrf_token_input.get('value')

# 构建登录数据
login_data = {
    "account": "test1",
    "password": "123456",
    "readAgreement": "1",
    "readAgreementValue": True,
    "rememberMeValue": True,
    "rememberMe": "1"
}
if csrf_token:
    login_data['csrf_token'] = csrf_token

# 发送 POST 请求进行登录
login_post_url = "https://www.yueshushu.top/StockApi/user/login"
response = session.post(login_post_url, json=login_data)

# 检查登录是否成功
if response.status_code == 200:
    # 检查登录成功后的页面元素
    loginContent = response.content.decode()
    loginJson = json.loads(loginContent)
    if 20000 == loginJson['code']:
        print("Login successful!")
    else:
        print("Login failed: Incorrect credentials or other issues.")
else:
    print(f"Login request failed with status code: {response.status_code}")

# 执行其他操作
# 假设登录后需要访问某个受保护的页面
params3 = {"code": "001318", "type":1}
protected_page_url = "https://www.yueshushu.top/StockApi/stockCrawler/getStockInfo"
response = session.get(protected_page_url,params = params3)

if response.status_code == 200:
    print("Accessing protected page:")
    print(response.text)
else:
    print(f"Protected page request failed with status code: {response.status_code}")

# 关闭会话
session.close()